import os
import os.path
import re

def get_config(branch):
    class Config:
        dirname = os.path.join(r"C:\Users\ezhechn\workspace\sqrdata\data\cppunit", branch.name, 'logs')
    return Config

def get_html(config, component, raw, old_raw, rank, old_rank):
    return str(raw)

def get_rank(config, component, raw):
    success, total = raw
    if total == -1: return 0.0

    Y_point = 5.0 if success == total else 1.0

    loc = component.line_of_code
    X_point = 1.0
    steps = [(1, 0.1), (loc/200, 0.4), (loc/200+1, 0.6), (loc/100, 0.8), (loc/100+1, 1)]
    for step in steps:
        if total >= step[0]:
            X_point = step[1]

    return X_point * Y_point

def get_latest_filename(filedir):
    files = os.listdir(filedir)
    latest_mtime = -1
    for f in files:
        mtime = os.path.getmtime(os.path.join(filedir, f))
        if mtime > latest_mtime:
            latest_mtime = mtime
            latest_filename = f

    return latest_filename

def get_raw(config, component):
    filename = get_latest_filename(config.dirname)
    filename = os.path.join(config.dirname, filename, "cppunit", "fdsfsc.html")

#<tr><td><img src="./ok.gif">guidriver</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0
#</td></tr><tr><td><img src="./ok.gif"><a href="./fsc/ifdriver.html">ifdriver</a></td><td>57</td><td>57</td><td>0</td><td>0</td><td>100 %</td><td>0
    with open(filename) as f:
        pattern = '<tr><td><img[^>]*>(<a[^>]*>)?%s(</a>)?</td><td>(\d+)</td><td>(\d+)</td>' % component.name
        m = re.search(pattern, f.read())
    total = int(m.group(3))
    success = int(m.group(4))
    return success, total

